package com.snap.vseries.fragment.cit;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.base.CitFragment;
import com.snap.vseries.bean.TestItem;
import com.snap.vseries.framework.MoleExecutor;
import com.snap.vseries.serial.Cmd;
import com.snap.vseries.ui.widget.TextButton;

import butterknife.BindView;

import static com.snap.vseries.AppConfig.DEVICE_TYPE;


@SuppressLint("ValidFragment")
public class FanFragment extends CitFragment {

    private final int position;
    @BindView(R.id.open_fan_tv)
    TextView openFanTv;
    @BindView(R.id.close_fan_tv)
    TextView closeFanTv;
    @BindView(R.id.pass_btn)
    TextButton passBtn;
    @BindView(R.id.not_pass_btn)
    TextButton notPassBtn;
    private TestItem testItem;

    public FanFragment(int position, TestItem testItem) {
        this.position = position;
        this.testItem = testItem;
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_cit_fan;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        openFanTv.setOnClickListener(v -> {
            if (!isTesting()) {
                setTesing(true);
                fanOperation(true);
            }
        });
        closeFanTv.setOnClickListener(v -> {
            if (!isTesting()) {
                setTesing(true);
                fanOperation(false);
            }
        });
        passBtn.setOnClickListener(v -> {
            testItem.setState(1);
            testItem.setComment("通过");
            notifyItem(position);
            fanOperation(false);
        });
        notPassBtn.setOnClickListener(v -> {
            testItem.setState(2);
            testItem.setComment("失败");
            notifyItem(position);
            fanOperation(false);
        });
    }

    private void fanOperation(boolean turnOn) {
        MoleExecutor.getInstance().execute(() -> {
            try {
                getSerialPortHelper().open();
                getSerialPortHelper().execute(Cmd.fan(DEVICE_TYPE, 1, turnOn));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                getSerialPortHelper().close();
                setTesing(false);
            }
        });
    }
}